package collector

import (
	"bufio"
	"io"
	"os"

	"github.com/prometheus/client_golang/prometheus"
)

func NewCollector(dataDir string) *RocketMQCollector {
	return &RocketMQCollector{
		count: prometheus.NewDesc(
			"rocketmq_count",
			"rocketmq_count",
			// 动态标签的key列表
			[]string{"group", "version", "type", "model"},
			// 静态标签
			prometheus.Labels{"module": "rocketmq"},
		),
		tps: prometheus.NewDesc(
			"rocketmq_tps",
			"rocketmq_tps",
			// 动态标签的key列表
			[]string{"group", "version", "type", "model"},
			// 静态标签
			prometheus.Labels{"module": "rocketmq"},
		),
		diff: prometheus.NewDesc(
			"rocketmq_diff_total",
			"rocketmq_diff_total",
			// 动态标签的key列表
			[]string{"group", "version", "type", "model"},
			// 静态标签
			prometheus.Labels{"module": "rocketmq"},
		),
		dataDir: dataDir,
	}
}

// 解析数据文件: data.txt  --> RocketMQMetricSet
// RocketMQMetricSet 转换成 prometheus format data
// 将prometheus format data 输出到标准输出
type RocketMQCollector struct {
	count   *prometheus.Desc
	tps     *prometheus.Desc
	diff    *prometheus.Desc
	dataDir string
}

func (c *RocketMQCollector) Describe(ch chan<- *prometheus.Desc) {
	ch <- c.count
	ch <- c.tps
	ch <- c.diff
}

func (c *RocketMQCollector) Collect(ch chan<- prometheus.Metric) {
	// 1. 读取文件
	f, err := os.Open(c.dataDir)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	// 使用bufio协助读取文件
	r := bufio.NewReader(f)
	for {
		line, _, err := r.ReadLine()
		// 文件读取完成
		if err == io.EOF {
			break
		}
		// 其他异常直接panic
		if err != nil {
			panic(err)
		}

		// 把一行数据转化为一个对象
		m := ParseLine(string(line))

		if m.Group != "#Group" {
			// 采集3种指标 []string{"group", "version", "type", "model"},
			ch <- prometheus.MustNewConstMetric(c.count, prometheus.GaugeValue, m.Float64Count(), m.Group, m.Version, m.Type, m.Model)
			ch <- prometheus.MustNewConstMetric(c.tps, prometheus.GaugeValue, m.Float64Tps(), m.Group, m.Version, m.Type, m.Model)
			ch <- prometheus.MustNewConstMetric(c.diff, prometheus.GaugeValue, m.Float64DiffTotal(), m.Group, m.Version, m.Type, m.Model)
		}
	}
}
